<template>
    <div class="blood-sugar-page">
        <!-- 顶部信息栏 -->
        <div class="top-info">
            <div class="time">
                <span>{{ currentTime }}</span>
            </div>
            <div class="sugar-value">
                <span class="big-value">{{ currentSugarValue }}</span>
                <span class="unit">mmol/L</span>
                <span v-if="sugarStatus === '正常'">正常</span>
                <span v-else>{{ sugarStatus }}</span>
            </div>
            <van-button type="primary" round class="record-btn" @click="showPopup = true">记录血糖</van-button>
        </div>
        <!-- 新增的图表容器 -->
        <div class="trend-chart">
            <div class="chart-title">血糖趋势(单位: mmol/L)</div>
            <div id="blood-sugar-chart" style="width: 100%; height: 300px;"></div>
            <div class="button-group">
                <van-button type="default" @click="showPreMeal">餐前</van-button>
                <van-button type="default" @click="showPostMeal">餐后</van-button>
            </div>
        </div>
        <!-- 血糖记录列表部分 -->
        <div class="record-list">
            <div class="list-title">血糖记录</div>
            <van-cell-group>
                <van-cell v-for="(record, index) in currentRecords" :key="index" class="record-item">
                    <div class="record-info">
                        <div class="date-time">
                            <span>{{ record.date }}</span>
                            <span class="time">{{ record.time }}</span>
                        </div>
                        <span v-if="record.status === '正常'">正常</span>
                        <span v-else>{{ record.status }}</span>
                        <div class="sugar-unit">
                            <span class="big-value">{{ record.currentSugarValue }}</span>
                            <span class="unit">mmol/L</span>
                        </div>
                        <div class="record-actions">
                            <van-icon name="edit" size="20" color="#7232dd" />
                            <van-icon name="delete" size="20" color="#ff4949" />
                        </div>
                    </div>
                </van-cell>
            </van-cell-group>
        </div>
        <!-- 新增弹出层 -->
        <van-popup v-model:show="showPopup" position="bottom" class="record-popup">
            <div class="popup-content">
                <div class="input-group">
                    <label>餐前血糖值：</label>
                    <van-field v-model="inputSugarValueBefore" type="number" placeholder="请输入餐前血糖值" />
                </div>
                <div class="input-group">
                    <label>餐后血糖值：</label>
                    <van-field v-model="inputSugarValueAfter" type="number" placeholder="请输入餐后血糖值" />
                </div>
                <div class="button-group">
                    <van-button type="default" @click="showPopup = false">取消</van-button>
                    <van-button type="primary" @click="handleSaveSugar">确定</van-button>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Cell, CellGroup, Button, Icon, Popup, Field } from 'vant';
import * as echarts from 'echarts';
import axios from 'axios';
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
// 控制弹出层显示隐藏
const showPopup = ref(false);
// 输入的餐前血糖值
const inputSugarValueBefore = ref('');
// 输入的餐后血糖值
const inputSugarValueAfter = ref('');

// 保存图表实例
const myChartRef = ref(null);
// 当前时间
const currentTime = ref('');
// 当前显示的血糖值
const currentSugarValue = ref('');
// 血糖状态
const sugarStatus = ref('');
// 血糖记录数组
const records = ref([]);
// 当前显示的记录数组
const currentRecords = ref([]);
// 当前显示的图表数据
const currentChartData = ref([]);

const handleSaveSugar = () => {
    if (inputSugarValueBefore.value && inputSugarValueAfter.value) {
        const newRecord = {
            date: new Date().toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }),
            time: new Date().toLocaleTimeString(),
            sugarValueBefore: inputSugarValueBefore.value,
            sugarValueAfter: inputSugarValueAfter.value,
            status: parseFloat(inputSugarValueAfter.value) > 7.0 ? '偏高' : '正常'
        };
        records.value.push(newRecord);

        // 调用添加血糖数据的接口
        const addData = {
            UserId: store.useStore.mId,
            UserName: store.useStore.userName,
            FastingBloodGlucose: parseFloat(inputSugarValueBefore.value),
            FastingTime: new Date(),
            PostprandialBloodGlucose: parseFloat(inputSugarValueAfter.value),
            PostprandialTime: new Date()
        };
        axios.post('http://localhost:5260/api/HealthMonitoringControllers/AddBloodSugar', addData)
            .then(response => {
                console.log('数据添加成功', response.data);
                // 调用显示方法
                showPreMeal();
            })
            .catch(error => {
                console.error('数据添加失败', error);
            });

        // 更新顶部显示的血糖值
        currentSugarValue.value = newRecord.sugarValueBefore;
        sugarStatus.value = newRecord.status;

        // 获取当前日期，用于添加到图表x轴数据
        const currentDate = new Date();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
        const day = String(currentDate.getDate()).padStart(2, '0');
        const newDate = `${month}/${day}`;

        // 更新图表数据
        const myChart = myChartRef.value;
        if (myChart) {
            // 创建全新的配置
            const newOption = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['血糖值']
                },
                xAxis: {
                    type: 'category',
                    data: [],
                    axisLabel: {
                        formatter: function (value) {
                            return value;
                        }
                    }
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '血糖值',
                        type: 'line',
                        data: [],
                        symbol: 'o',
                        lineStyle: {
                            color: '#5B8FF9'
                        },
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: 'rgba(91, 143, 249, 0.4)' },
                                { offset: 1, color: 'rgba(91, 143, 249, 0)' }
                            ])
                        }
                    }
                ]
            };

            newOption.xAxis.data.push(newDate);
            newOption.series[0].data.push(parseFloat(inputSugarValueBefore.value));

            // 确保 x 轴数据正确设置
            const xAxisData = myChart.getOption().xAxis.data;
            if (Array.isArray(xAxisData)) {
                xAxisData.reverse();
                const option = myChart.getOption();
                option.xAxis.data = xAxisData;
                myChart.setOption(option);
            }
        }

        // 清空文本框
        inputSugarValueBefore.value = '';
        inputSugarValueAfter.value = '';

        showPopup.value = false;
    }
};

const showPreMeal = () => {
    currentSugarValue.value = records.value.length > 0 ? records.value[records.value.length - 1].sugarValueBefore : '';
    currentRecords.value = records.value.map(record => ({
        ...record,
        currentSugarValue: record.sugarValueBefore
    }));
    currentChartData.value = records.value.map(record => parseFloat(record.sugarValueBefore));
    updateChart();
};

const showPostMeal = () => {
    currentSugarValue.value = records.value.length > 0 ? records.value[records.value.length - 1].sugarValueAfter : '';
    currentRecords.value = records.value.map(record => ({
        ...record,
        currentSugarValue: record.sugarValueAfter
    }));
    currentChartData.value = records.value.map(record => parseFloat(record.sugarValueAfter));
    updateChart();
};

const updateChart = () => {
    const myChart = myChartRef.value;
    if (myChart) {
        // 创建全新的配置
        const newOption = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['血糖值']
            },
            xAxis: {
                type: 'category',
                data: [],
                axisLabel: {
                    formatter: function (value) {
                        return value;
                    }
                }
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '血糖值',
                    type: 'line',
                    data: [],
                    symbol: 'o',
                    lineStyle: {
                        color: '#5B8FF9'
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(91, 143, 249, 0.4)' },
                            { offset: 1, color: 'rgba(91, 143, 249, 0)' }
                        ])
                    }
                }
            ]
        };

        newOption.xAxis.data = currentRecords.value.map(record => record.date);
        newOption.series[0].data = currentChartData.value;

        myChart.setOption(newOption);
    }
};

onMounted(() => {
    const chartDom = document.getElementById('blood-sugar-chart');
    const myChart = echarts.init(chartDom);

    // 调用查询血糖数据的接口
    axios.get('http://localhost:5223/api/HealthMonitoring/GetBloodSugar', {
        params: {
            UserId: store.useStore.mId
        }
    })
        .then(response => {
            console.log('查询响应数据:', response.data);
            if (response.data && response.data.data && response.data.data.length > 0) {
                records.value = response.data.data.map(item => {
                    const fastingDate = new Date(item.fastingTime);
                    const postprandialDate = new Date(item.postprandialTime);
                    const date = `${String(fastingDate.getMonth() + 1).padStart(2, '0')}/${String(fastingDate.getDate()).padStart(2, '0')}`;
                    const time = `${fastingDate.getHours()}:${String(fastingDate.getMinutes()).padStart(2, '0')}:${String(fastingDate.getSeconds()).padStart(2, '0')}`;
                    return {
                        date: date,
                        time: time,
                        sugarValueBefore: item.fastingBloodGlucose,
                        sugarValueAfter: item.postprandialBloodGlucose,
                        status: parseFloat(item.postprandialBloodGlucose) > 7.0 ? '偏高' : '正常'
                    };
                });

                // 更新图表数据
                let xAxisData = records.value.map(record => record.date);
                const preMealData = records.value.map(record => record.sugarValueBefore);
                const postMealData = records.value.map(record => record.sugarValueAfter);

                const myChart = myChartRef.value;
                if (myChart) {
                    // 创建全新的配置
                    const newOption = {
                        tooltip: {
                            trigger: 'axis'
                        },
                        legend: {
                            data: ['血糖值']
                        },
                        xAxis: {
                            type: 'category',
                            data: [],
                            axisLabel: {
                                formatter: function (value) {
                                    return value;
                                }
                            }
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [
                            {
                                name: '血糖值',
                                type: 'line',
                                data: [],
                                symbol: 'o',
                                lineStyle: {
                                    color: '#5B8FF9'
                                },
                                areaStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: 'rgba(91, 143, 249, 0.4)' },
                                        { offset: 1, color: 'rgba(91, 143, 249, 0)' }
                                    ])
                                }
                            }
                        ]
                    };

                    newOption.xAxis.data = xAxisData;
                    newOption.series[0].data = preMealData;

                    // 对x轴数据进行倒序
                    if (Array.isArray(xAxisData)) {
                        xAxisData.reverse();
                        newOption.xAxis.data = xAxisData;
                        myChart.setOption(newOption);
                    }
                }

                // 更新顶部时间显示
                currentTime.value = new Date().toLocaleString('zh-CN', { month: '2-digit', day: '2-digit' });

                // 默认显示餐前数据
                showPreMeal();
            }
        })
        .catch(error => {
            console.error('数据查询失败', error);
        });

    // 保存图表实例到响应式变量
    myChartRef.value = myChart;

    // 新增监听窗口resize事件
    window.addEventListener('resize', () => {
        myChart.resize();
    });
});
</script>

<style scoped>
/* 整体页面背景色 */
.blood-sugar-page {
    background-color: #f0f9eb;
    /* 浅绿色系，类似第二张图背景色 */
    padding: 16px;
}

/* 顶部信息栏 */
.top-info {
    background-color: #32cd32;
    /* 亮绿色，类似第二张图顶部颜色 */
    color: white;
    padding: 20px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    /* 改为垂直排列 */
    align-items: center;
}

/* 时间显示 */
.time {
    font-size: 12px;
    /* 适当减小字体 */
}

/* 血糖值显示 */
.sugar-value {
    text-align: center;
    margin-bottom: 10px;
    /* 增加间距 */
}

.big-value {
    font-size: 32px;
    /* 适当减小字体 */
    font-weight: bold;
}

.unit {
    font-size: 12px;
}

/* 记录血糖按钮 */
.record-btn {
    width: 120px;
    height: 36px;
    background-color: #ffd700;
    /* 黄色按钮 */
    color: #000;
    border: none;
}

/* 图表区域 */
.trend-chart {
    background-color: white;
    border-radius: 8px;
    padding: 16px;
    margin-top: 16px;
}

.chart-title {
    font-size: 16px;
    margin-bottom: 8px;
}

/* 按钮组样式 */
.button-group {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-top: 10px;
}

/* 血糖记录列表 */
.record-list {
    background-color: white;
    border-radius: 8px;
    padding: 16px;
    margin-top: 16px;
}

.list-title {
    font-size: 16px;
    /* 适当减小字体 */
    margin-bottom: 8px;
}

.record-item {
    padding: 8px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #ebebeb;
    background-color: #ecf5ff;
    /* 添加背景色模拟卡片效果 */
    border-radius: 10px;
    /* 圆角 */
    padding: 12px;
    /* 内边距 */
}

.record-info {
    display: flex;
    align-items: center;
}

.date-time {
    display: flex;
    flex-direction: column;
    margin-right: 16px;
}

.sugar-unit {
    display: flex;
    flex-direction: column;
    margin-right: 16px;
}

.record-time {
    font-size: 12px;
    /* 适当减小字体 */
}

.record-sugar-value {
    font-size: 16px;
    /* 适当调整字体 */
}

.record-actions {
    display: flex;
}

/* 弹出层样式 */
.record-popup {
    background-color: white;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    padding: 20px;
}

.popup-content {
    display: flex;
    flex-direction: column;
}

.input-group {
    margin-bottom: 16px;
}

.button-group {
    display: flex;
    justify-content: flex-end;
}
</style>